package com.cw.jeeyt.service.impl.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.common.enums.EnumDataJavaType;
import com.cw.jeeyt.common.enums.EnumYn;
import com.cw.jeeyt.service.bo.security.SecurityUserBo;
import com.cw.jeeyt.service.bo.system.SystemColumnInfoBo;
import com.cw.jeeyt.service.bo.system.SystemDataEntryBo;
import com.cw.jeeyt.core.util.SessionUtil;
import com.cw.jeeyt.dao.intf.system.SystemColumnInfoDao;
import com.cw.jeeyt.dao.model.system.SystemColumnInfoDo;
import com.cw.jeeyt.service.converter.system.SystemColumnInfoConverter;
import com.cw.jeeyt.service.intf.system.SystemColumnInfoService;
import com.cw.jeeyt.service.intf.system.SystemDataEntryService;
import com.cw.jeeyt.service.intf.system.SystemTableInfoService;
import com.cw.lang.mybatis.dto.PageInfo;
import com.cw.lang.common.utils.SequenceTool;

/**
 * 表字段信息业务实现类
 *
 * @author chenw
* @version 1.0.0
 */
@Service
public class SystemColumnInfoServiceImpl implements SystemColumnInfoService {

    private static final Logger logger = LoggerFactory.getLogger(SystemColumnInfoServiceImpl.class);
    @Autowired
    private SystemColumnInfoDao systemColumnInfoDao;//表字段信息数据库操作接口
    @Autowired
    private SystemDataEntryService systemDataEntryService;//数据条目业务实现类
    @Autowired
    private SystemTableInfoService systemTableInfoService;//表模型业务实现类

    /**
     * 新增SystemColumnInfo
     *
     * @param systemColumnInfoBo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertSystemColumnInfo(SystemColumnInfoBo systemColumnInfoBo) throws Exception {

        SecurityUserBo securityUser = SessionUtil.getSessionUser();
        if (securityUser == null) {
            throw new Exception("获取用户登录信息出错");
        }
        if (systemColumnInfoBo == null) {
            logger.error("表字段信息为空");
            return;
        }
        SystemColumnInfoDo systemColumnInfo = SystemColumnInfoConverter.bo2Do(systemColumnInfoBo);
        systemColumnInfo.setId(SequenceTool.nextLongId());
        systemColumnInfo.setCreateBy(securityUser.getId());
        systemColumnInfo.setCreateDate(new Date());
        systemColumnInfo.setUpdateBy(securityUser.getId());
        systemColumnInfo.setUpdateDate(new Date());
        systemColumnInfoDao.insertSystemColumnInfo(systemColumnInfo);
        //保存字段信息以后判断是否是主键，如果是，则更新表模型信息中的主键
        String isPk = systemColumnInfo.getIsPk();
        if (EnumYn.Y.getCode()
            .equals(isPk)) {
            Long pkId = systemColumnInfo.getId();
            String columnType = systemColumnInfo.getColumnType();
            systemTableInfoService.updatePkId(systemColumnInfo.getTableId(), pkId, EnumDataJavaType.find(columnType)
                .getCode());
        }
    }

    /**
     * 更新SystemColumnInfo信息
     *
     * @param systemColumnInfoBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSystemColumnInfo(SystemColumnInfoBo systemColumnInfoBo) throws Exception {

        if (systemColumnInfoBo == null) {
            logger.error("表字段信息为空");
            return;
        }
        SecurityUserBo userVo = SessionUtil.getSessionUser();
        SystemColumnInfoDo systemColumnInfo = SystemColumnInfoConverter.bo2Do(systemColumnInfoBo);
        systemColumnInfo.setUpdateBy(userVo.getId());
        systemColumnInfo.setUpdateDate(new Date());
        systemColumnInfoDao.updateSystemColumnInfo(systemColumnInfo);
    }

    /**
     * 删除SystemColumnInfo
     *
     * @param systemColumnInfoBo
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteSystemColumnInfo(SystemColumnInfoBo systemColumnInfoBo) throws Exception {
        if (systemColumnInfoBo == null) {
            logger.error("表字段信息为空");
            return;
        }
        systemColumnInfoDao.deleteSystemColumnInfo(SystemColumnInfoConverter.bo2Do(systemColumnInfoBo));

    }

    /**
     * 根据表id删除表字段信息
     *
     * @param tableId 表id
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByTableId(String tableId) throws Exception {
        if (StringUtils.isEmpty(tableId)) {
            logger.error("表id为空");
            return;
        }
        systemColumnInfoDao.deleteByTableId(tableId);
    }

    /**
     * 分页查询SystemColumnInfo
     *
     * @param systemColumnInfoBo
     * @param startNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<SystemColumnInfoBo> queryByPage(SystemColumnInfoBo systemColumnInfoBo, Integer startNum,
        Integer pageSize) throws Exception {
        PageInfo<SystemColumnInfoDo> pageInfo = systemColumnInfoDao.queryByPage(
            SystemColumnInfoConverter.bo2Do(systemColumnInfoBo), startNum, pageSize);
        return new PageInfo<>(pageInfo, SystemColumnInfoConverter.doList2BoList(pageInfo.getList()));
    }

    /**
     * 根据表id查询主键字段信息
     *
     * @param tableId 表id
     * @return
     * @throws Exception
     */
    @Override
    public List<SystemColumnInfoBo> queryPkColumnInfoListByTableId(String tableId) throws Exception {

        return SystemColumnInfoConverter.doList2BoList(systemColumnInfoDao.queryPkColumnInfoListByTableId(tableId));
    }

    /**
     * 根据表模型id查询表字段信息
     */
    @Override
    public List<SystemColumnInfoBo> queryColumnInfoListByTableId(String tableId) throws Exception {
        return SystemColumnInfoConverter.doList2BoList(systemColumnInfoDao.queryColumnInfoListByTableId(tableId));
    }

    /**
     * 根据主键查询SystemColumnInfo信息
     *
     * @param id
     * @return
     */
    @Override
    public SystemColumnInfoBo getSystemColumnInfoById(String id) throws Exception {

        return SystemColumnInfoConverter.do2Bo(systemColumnInfoDao.getSystemColumnInfoById(id));
    }

    /**
     * 校验表字段是否存在
     */
    @Override
    public SystemColumnInfoBo checkSystemColumnCode(SystemColumnInfoBo systemColumnInfoBo) throws Exception {

        SystemColumnInfoDo systemColumnInfo = SystemColumnInfoConverter.bo2Do(systemColumnInfoBo);
        SystemColumnInfoDo new_systemColumnInfo = systemColumnInfoDao.checkSystemColumnCode(systemColumnInfo);
        if (new_systemColumnInfo == null) {
            return null;
        }
        SystemColumnInfoBo new_systemColumnInfoBo = SystemColumnInfoConverter.do2Bo(new_systemColumnInfo);
        return new_systemColumnInfoBo;
    }

    /**
     * 导入数据条目到模型字段表中
     *
     * @param tableId 表模型id
     * @param dataEntryStr 数据条目字符串
     * @throws Exception
     */
    @Override
    public void importDataEntry(String tableId, String dataEntryStr, String isPk) throws Exception {
        String[] dataEntryArr = dataEntryStr.split(",");
        List<SystemColumnInfoDo> columnInfoList = new ArrayList<>();
        Long userId = SessionUtil.getSessionUserId();
        if (dataEntryArr != null && dataEntryArr.length > 0) {
            for (String dataEntryId : dataEntryArr) {
                SystemDataEntryBo systemDataEntryBo = systemDataEntryService.getSystemDataEntryById(dataEntryId);
                if (systemDataEntryBo != null) {
                    SystemColumnInfoDo systemColumnInfo = new SystemColumnInfoDo();
                    systemColumnInfo.setId(SequenceTool.nextLongId());
                    systemColumnInfo.setIsPk(isPk);
                    systemColumnInfo.setTableId(tableId);
                    systemColumnInfo.setCreateBy(userId);
                    systemColumnInfo.setCreateDate(new Date());
                    systemColumnInfo.setUpdateBy(userId);
                    systemColumnInfo.setUpdateDate(new Date());
                    systemColumnInfo.setColumnCode(systemDataEntryBo.getDataJavaCode());
                    systemColumnInfo.setColumnName(systemDataEntryBo.getDataName());
                    systemColumnInfo.setColumnLength(systemDataEntryBo.getDataLength());
                    systemColumnInfo.setColumnType(systemDataEntryBo.getDataJavaType());
                    systemColumnInfo.setColumnSqlCode(systemDataEntryBo.getDataCode());
                    systemColumnInfo.setColumnSqlType(systemDataEntryBo.getDataType());
                    systemColumnInfo.setColumnComment(systemDataEntryBo.getDataComment());
                    systemColumnInfo.setIsDict(EnumYn.N.getCode());
                    systemColumnInfo.setIsFormColumn(EnumYn.Y.getCode());
                    systemColumnInfo.setIsListColumn(EnumYn.Y.getCode());
                    systemColumnInfo.setIsQueryColumn(EnumYn.Y.getCode());
                    columnInfoList.add(systemColumnInfo);
                }
            }
            systemColumnInfoDao.insertSystemColumnInfoBat(columnInfoList);
        }

    }

    /**
     * 保存表模型字段页面配置信息
     *
     * @param columnJson 页面配置json信息
     * @throws Exception
     */
    @Override
    public void saveColumnInfoPageConfig(String columnJson) throws Exception {

        if (StringUtils.isEmpty(columnJson)) {
            logger.info("--页面配置json信息为空--");
            return;
        }
        JSONObject columns = JSON.parseObject(columnJson);
        JSONArray columnList = (JSONArray) columns.get("columnJson");
        if (columnList != null && !columnList.isEmpty()) {
            List<SystemColumnInfoBo> systemColumnInfoBos = JSON.parseArray(columnList.toJSONString(),
                SystemColumnInfoBo.class);
            for (SystemColumnInfoBo sci : systemColumnInfoBos) {
                SystemColumnInfoDo systemColumnInfo = SystemColumnInfoConverter.bo2Do(sci);
                systemColumnInfo.setUpdateBy(SessionUtil.getSessionUserId());
                systemColumnInfo.setUpdateDate(new Date());
            }
            systemColumnInfoDao.updateList(SystemColumnInfoConverter.boList2DoList(systemColumnInfoBos));
        }
    }

    @Override
    public void insertSystemColumnInfoBat(List<SystemColumnInfoBo> systemColumnInfoList) {
        List<SystemColumnInfoDo> columnInfoList = new ArrayList<SystemColumnInfoDo>();
        for (SystemColumnInfoBo systemColumnInfo : systemColumnInfoList) {
            SystemColumnInfoDo sci = SystemColumnInfoConverter.bo2Do(systemColumnInfo);
            sci.setId(SequenceTool.nextLongId());
            columnInfoList.add(sci);
        }
        systemColumnInfoDao.insertSystemColumnInfoBat(columnInfoList);
    }

    @Override
    public List<SystemColumnInfoBo> queryDictColumnInfoListByTableId(String tableId) {
        return SystemColumnInfoConverter.doList2BoList(systemColumnInfoDao.queryDictColumnInfoListByTableId(tableId));
    }
}
